package com.cmcc.linlaker.ui.query;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.LoadingActivity;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.DictBean;
import com.cmcc.linlaker.bean.ImageUploadBean;
import com.cmcc.linlaker.crop.ClipImageActivity;
import com.cmcc.linlaker.crop.util.ActivityResultHelper;
import com.cmcc.linlaker.fragment.RoundFragment;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.query.fragment.FarmerFragment;
import com.cmcc.linlaker.ui.upload.UploadSelfDealDetailActivity;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter;
import com.cmcc.linlaker.ui.upload.bean.ImageBean;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.DensityUtil;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.PhotoUtils;
import com.cmcc.linlaker.utils.PictureUtil;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.StringUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.view.GridSpacingItemDecoration;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.OnGetPoiResultListener;
import com.tianditu.android.maps.PoiInfo;
import com.tianditu.android.maps.PoiSearch;
import com.tianditu.android.maps.TErrorCode;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zyyoona7.picker.DatePickerView;
import com.zyyoona7.picker.base.BaseDatePickerView;
import com.zyyoona7.picker.ex.DayWheelView;
import com.zyyoona7.picker.ex.MonthWheelView;
import com.zyyoona7.picker.ex.YearWheelView;
import com.zyyoona7.picker.listener.OnDateSelectedListener;
import com.zyyoona7.wheel.WheelView;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class NewHouseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_house);

        BarUtils.initStatusBar(this);

        initView();
    }

    private double latitude, longitude;

    private EditText edit_address, editApplyMobile, editApproval, editTotalArea, editFloor, editHouseOwner, editBuildingArea;
    private TextView textApplyTime, textForm, textIsProtected, textIsControl, textNature;

    private ImageAdapter adapter;
    private List<ImageBean> bmpList = new ArrayList<>();
    private RecyclerView recycler_pic;

    public void initView() {
        recycler_pic = findViewById(R.id.recycler_pic);
        setRecyclerView(recycler_pic, bmpList);
        addButton();

        textNature = findViewById(R.id.textNature);
        edit_address = findViewById(R.id.edit_address);
        textIsProtected = findViewById(R.id.textIsProtected);
        textIsControl = findViewById(R.id.textIsControl);
        editApproval = findViewById(R.id.editApproval);
        textForm = findViewById(R.id.textForm);
        editApplyMobile = findViewById(R.id.editApplyMobile);
        editTotalArea = findViewById(R.id.editTotalArea);
        editFloor = findViewById(R.id.editFloor);
        editHouseOwner = findViewById(R.id.editHouseOwner);
        editBuildingArea = findViewById(R.id.editBuildingArea);
        textApplyTime = findViewById(R.id.textApplyTime);
    }

    private void setRecyclerView(final RecyclerView recycler_view, final List<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(this, 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(this, 10), true));
        adapter = new ImageAdapter(this, itemList);
        adapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures();
                } else {
                    Intent intent = new Intent(NewHouseActivity.this, ImageScanActivity.class);
                    intent.putExtra("imageList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic(position);
            }
        });
        recycler_view.setAdapter(adapter);
    }

    /**
     * 选择图片
     */
    public void selectPictures() {
        showSelectDialog();
    }

    private void showSelectDialog() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                NewHouseActivity.this);
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto();
                        } else if (which == 1) {// 相册
                            choosePhoto();
                        }

                    }
                }).create().show();
    }

    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;
    public static final int RC_CROP_PHOTO = 3;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 拍照
     */
    private void takePhoto() {
        imageUri = Uri.fromFile(fileUri);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(NewHouseActivity.this, "com.cmcc.linlaker.fileprovider", fileUri);
        }

        PhotoUtils.takePicture(this, imageUri, RC_TAKE_PHOTO);
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        PhotoUtils.openPic(this, RC_CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RC_TAKE_PHOTO) {
                gotoClipActivity(Uri.fromFile(fileUri));
//                cropImageUri = Uri.fromFile(fileCropUri);

//                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CHOOSE_PHOTO) {
                gotoClipActivity(data.getData());

//                cropImageUri = Uri.fromFile(fileCropUri);
//                Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    newUri = FileProvider.getUriForFile(this, "com.cmcc.linlaker.fileprovider", new File(newUri.getPath()));
//                }
//
//                PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CROP_PHOTO) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        }
    }

    /**
     * 获取图片url
     */
    private String getImageListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < imageList.size(); i++) {
            if (i < imageList.size() - 1) {
                stringBuffer.append(imageList.get(i) + ",");
            } else {
                stringBuffer.append(imageList.get(i));
            }
        }

        return stringBuffer.toString();
    }

    /**
     * 删除图片
     */
    private void deletePic(int position) {
        imageList.remove(position);
        bmpList.remove(position);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加按钮
     */
    private void addButton() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        bmpList.add(bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.path = StringUtils.bitmaptoString(bmp);
        bean.type = 1;
        bmpList.add(bmpList.size() - 1, bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        ClipImageActivity.goToClipActivity(NewHouseActivity.this, uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, NewHouseActivity.this);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        });
    }

    private ArrayList<String> imageList = new ArrayList<>();

    private void uploadPic(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            imageList.add(bean.url);
                        }

                    }
                });
    }

    public void back(View view) {
        finish();
    }

    private int naturePos;
    private int formPos;
    private int isTypePos;
    private int isRegionPos;

    /**
     * 选择建设性质
     */
    public void selectNature(View view) {
        showDict(findViewById(R.id.layout_add_house), "nature");
    }

    /**
     * 选择建设形式
     */
    public void selectForm(View view) {
        showDict(findViewById(R.id.layout_add_house), "construction_form");
    }


    /**
     * 选择项目类型
     */
    public void selectIsProtected(View view) {
        showDict(findViewById(R.id.layout_add_house), "type");
    }

    /**
     * 选择所属地区
     */
    public void selectIsControl(View view) {
        showDict(findViewById(R.id.layout_add_house), "region");
    }


    private PopupWindow popupWindow;

    private void showDict(View view, final String tag) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_dict, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);


        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setButtonListeners(layout, tag);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });
    }

    private void setButtonListeners(RelativeLayout layout, final String tag) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final WheelView wheelview = layout.findViewById(R.id.wheelview);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

                if (tag.equals("nature")) {
                    naturePos = wheelview.getSelectedItemPosition();
                    textNature.setText(LinhuApp.natureList.get(naturePos).dictLabel);
                } else if (tag.equals("construction_form")) {
                    formPos = wheelview.getSelectedItemPosition();
                    textForm.setText(LinhuApp.formList.get(formPos).dictLabel);
                } else if (tag.equals("region")) {
                    isRegionPos = wheelview.getSelectedItemPosition();
                    textIsControl.setText(LinhuApp.regionList.get(isRegionPos).name);
                } else if (tag.equals("type")) {
                    isTypePos = wheelview.getSelectedItemPosition();
                    textIsProtected.setText(getTypeList().get(isTypePos).dictLabel);
                }
            }
        });

        //设置数据
        if (tag.equals("nature")) {
            wheelview.setData(LinhuApp.natureList);
        } else if (tag.equals("construction_form")) {
            wheelview.setData(LinhuApp.formList);
        } else if (tag.equals("region")) {
            wheelview.setData(LinhuApp.regionList);
        } else if (tag.equals("type")) {
            wheelview.setData(getTypeList());
        }

        //尽请使用各种方法
        wheelview.setTextSize(20f, true);
        wheelview.setNormalItemTextColor(0xff666666);
        wheelview.setSelectedItemTextColor(0xff000000);
        wheelview.setDividerPaddingForWrap(13f);

        if (tag.equals("nature")) {
            wheelview.setSelectedItemPosition(naturePos);
        } else if (tag.equals("construction_form")) {
            wheelview.setSelectedItemPosition(formPos);
        } else if (tag.equals("region")) {
            wheelview.setSelectedItemPosition(isRegionPos);
        } else if (tag.equals("type")) {
            wheelview.setSelectedItemPosition(isTypePos);
        }
    }

    private List<DictBean.DictData> getTypeList() {
        List<DictBean.DictData> typeListNew = new ArrayList<>();
        for (DictBean.DictData dictData : LinhuApp.typeList) {
            if (dictData.dictLabel.equals("其他") || dictData.dictLabel.equals("农民建房")) {
                typeListNew.add(dictData);
            }
        }
        return typeListNew;
    }


    private String applyTime;

    /**
     * 选择申请时间
     */
    public void selectApplyTime(View view) {
        showDatePicker(findViewById(R.id.layout_add_house), "applyTime");
    }


    private PopupWindow datePopupWindow;

    private void showDatePicker(View view, final String tag) {
        if (datePopupWindow != null && datePopupWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_date_picker, null);
        datePopupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);


        //点击空白处时，隐藏掉pop窗口
        datePopupWindow.setFocusable(true);
        datePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        datePopupWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        datePopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setDatePickerButtonListeners(layout, tag);
        datePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });
    }

    private void setDatePickerButtonListeners(RelativeLayout layout, final String tag) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final DatePickerView datePickerView = layout.findViewById(R.id.datePickerView);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePopupWindow.dismiss();
            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePopupWindow.dismiss();

                if (tag.equals("applyTime")) {
                    textApplyTime.setText(applyTime);
                }
            }
        });

        datePickerView.setOnDateSelectedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(BaseDatePickerView datePickerView, int year, int month, int day, @Nullable Date date) {
                if (tag.equals("applyTime")) {
                    applyTime = year + "-" + parseNumber(month) + "-" + parseNumber(day);
                }
            }
        });

        //尽请使用各种方法
        datePickerView.setNormalItemTextColor(0xff666666);
        datePickerView.setSelectedItemTextColor(0xff000000);
        datePickerView.setDividerHeight(12f);
        datePickerView.setTextSize(20, true);
        datePickerView.setShowLabel(false);
        YearWheelView yearWv3 = datePickerView.getYearWv();
        MonthWheelView monthWv3 = datePickerView.getMonthWv();
        DayWheelView dayWv3 = datePickerView.getDayWv();
        yearWv3.setIntegerNeedFormat("%d年");
        monthWv3.setIntegerNeedFormat("%02d月");
        dayWv3.setIntegerNeedFormat("%02d日");

        if (tag.equals("applyTime")) {
            applyTime = yearWv3.getSelectedYear() + "-" + parseNumber(monthWv3.getSelectedMonth()) + "-" + parseNumber(dayWv3.getSelectedDay());
        }

        yearWv3.setTextBoundaryMargin(16, true);
        monthWv3.setTextBoundaryMargin(16, true);
        dayWv3.setTextBoundaryMargin(16, true);
        datePickerView.setDrawSelectedRect(true);
        datePickerView.setSelectedRectColor(Color.parseColor("#F5F5F5"));
    }

    /**
     * 数字小于10 前面加0
     */
    private String parseNumber(int number) {
        if (number < 10) {
            return "0" + number;
        } else {
            return number + "";
        }
    }

    private GeoPoint geoPoint;

    private void initLocation() {
        geoPoint = RoundFragment.mMyLocation.getMyLocation();

        latitude = geoPoint.getLatitudeE6();
        longitude = geoPoint.getLongitudeE6();

        //逆地理编码类，根据输入的点坐标，返回相应的地理信息
        TGeoDecode tGeoDecode = new TGeoDecode(new OnGeoResultListener());
        tGeoDecode.search(geoPoint);
    }

    class MyOverlay extends MyLocationOverlay {
        public MyOverlay(Context context, MapView mapView) {
            super(context, mapView);
        }

        /*
         * 处理在"我的位置"上的点击事件
         */
        protected boolean dispatchTap() {
            return true;
        }

        @Override
        public void onLocationChanged(Location location) {
            super.onLocationChanged(location);
        }
    }

    /**
     * 逆地理编码回调结果监听
     */
    class OnGeoResultListener implements TGeoDecode.OnGeoResultListener {

        @Override
        public void onGeoDecodeResult(TGeoAddress tGeoAddress, int errorCode) {

            if (TErrorCode.OK == errorCode) {
                // 查询点相关信息
                edit_address.setText(tGeoAddress.getFullName());
            } else {
                ToastUtils.showText(NewHouseActivity.this, "位置查询出错，请稍后重试");
            }
        }
    }

    /**
     * 获取定位
     */
    public void getLocationInfo(View view) {
        initLocation();
    }

    private PoiSearch mPoiSearch;

    /**
     * 根据地址查询经纬度
     */
    private void getLatLng(String address) {
        mPoiSearch = new PoiSearch(this, new OnGetPoiResultListener() {
            @Override
            public void OnGetPoiResult(ArrayList<PoiInfo> arrayList, ArrayList<PoiSearch.ProvinceInfo> arrayList1, String s, int i) {
                if (arrayList != null && arrayList.size() > 0) {
                    longitude = arrayList.get(0).mPoint.getLongitudeE6();
                    latitude = arrayList.get(0).mPoint.getLatitudeE6();

                    upload();
                } else {
                    ToastUtils.showText(NewHouseActivity.this, "请输入正确的地址信息");
                }
            }
        }, RoundFragment.mMapView);
        mPoiSearch.search(address, null, null);
    }

    /**
     * 新增项目
     */
    public void addProject(View view) {
        String address = edit_address.getText().toString();
        if (TextUtils.isEmpty(address)) {
            ToastUtils.showText(this, "请输入建设地址");
        } else {
            if (latitude != 0 && longitude != 0) {
                upload();
            } else {
                getLatLng(address);
            }

        }
    }


    /**
     * 新增
     */
    private void upload() {
        if (TextUtils.isEmpty(editHouseOwner.getText().toString())) {
            ToastUtils.showText(this, "请输入项目名称");
            editHouseOwner.requestFocus();
            Utils.showSoftInputFromWindow(editHouseOwner);
            return;
        }

//        if (TextUtils.isEmpty(editApplyMobile.getText().toString())) {
//            ToastUtils.showText(this, "请输入申请人联系电话");
//            editApplyMobile.requestFocus();
//            Utils.showSoftInputFromWindow(editApplyMobile);
//            return;
//        }

        if (TextUtils.isEmpty(textApplyTime.getText().toString())) {
            ToastUtils.showText(this, "请选择申请时间");
            return;
        }

        if (TextUtils.isEmpty(textNature.getText().toString())) {
            ToastUtils.showText(this, "请选择建设性质");
            return;
        }

        if (TextUtils.isEmpty(textForm.getText().toString())) {
            ToastUtils.showText(this, "请选择建设形式");
            return;
        }

        if (TextUtils.isEmpty(edit_address.getText().toString())) {
            ToastUtils.showText(this, "请输入建设地址");
            edit_address.requestFocus();
            Utils.showSoftInputFromWindow(edit_address);
            return;
        }

        if (TextUtils.isEmpty(textIsProtected.getText().toString())) {
            ToastUtils.showText(this, "请选择项目类型");
            return;
        }

        if (TextUtils.isEmpty(textIsControl.getText().toString())) {
            ToastUtils.showText(this, "请选择所属地区");
            return;
        }

        if (TextUtils.isEmpty(editBuildingArea.getText().toString())) {
            ToastUtils.showText(this, "请输入总占地面积");
            editBuildingArea.requestFocus();
            Utils.showSoftInputFromWindow(editBuildingArea);
            return;
        }

        if (TextUtils.isEmpty(editTotalArea.getText().toString())) {
            ToastUtils.showText(this, "请输入总建筑面积");
            editTotalArea.requestFocus();
            Utils.showSoftInputFromWindow(editTotalArea);
            return;
        }

        if (TextUtils.isEmpty(editFloor.getText().toString())) {
            ToastUtils.showText(this, "请输入建筑层次");
            editFloor.requestFocus();
            Utils.showSoftInputFromWindow(editFloor);
            return;
        }

        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("address", edit_address.getText().toString());
        params.put("approval", editApproval.getText().toString());
        params.put("form", LinhuApp.formList.get(formPos).dictValue);
        params.put("region", LinhuApp.regionList.get(isRegionPos).id);
        params.put("type", getTypeList().get(isTypePos).dictValue);
//        params.put("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
//        params.put("longitude", Utils.formatLatLng((float) (longitude / 1E6)));
        params.put("latitude", latitude + "");
        params.put("longitude",longitude + "");
        params.put("nature", LinhuApp.natureList.get(naturePos).dictValue);
        params.put("applyMobile", editApplyMobile.getText().toString());
        params.put("registerTime", textApplyTime.getText().toString());
        params.put("floor", editFloor.getText().toString());
        params.put("name", editHouseOwner.getText().toString());
        params.put("totalBuildingArea", editBuildingArea.getText().toString());
        params.put("totalLand", editTotalArea.getText().toString());
        params.put("fileUrls", getImageListStr());
        params.put("projectSort", "1");


        helper.sendPOSTRequest(ApiDefine.PROJECT_ADD, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
                        ToastUtils.showText(NewHouseActivity.this, "新增农民建房成功");
                        FarmerFragment.isAddedNew = true;
                        finish();
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(NewHouseActivity.this);
                    } else {
                        ToastUtils.showText(NewHouseActivity.this, bean.msg);
                    }
                }
            }
        });
    }
}
